Page({
  data: {
    backendUrl: 'http://127.0.0.1:88/api/user/',
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
    showOld: false,
    showNew: false,
    showConfirm: false
  },

  // 切换密码显示状态
  toggleOldPwd() {
    this.setData({ showOld: !this.data.showOld });
  },

  toggleNewPwd() {
    this.setData({ showNew: !this.data.showNew });
  },

  toggleConfirmPwd() {
    this.setData({ showConfirm: !this.data.showConfirm });
  },

  // 输入框事件处理
  inputOldPassword(e) {
    this.setData({ oldPassword: e.detail.value });
  },

  inputNewPassword(e) {
    this.setData({ newPassword: e.detail.value });
  },

  inputConfirmPassword(e) {
    this.setData({ confirmPassword: e.detail.value });
  },

  // 修改密码
  handleChangePassword() {
    const { oldPassword, newPassword, confirmPassword } = this.data;
    const userInfo = wx.getStorageSync('userInfo');
    
    // 表单验证
    if (!oldPassword || !newPassword || !confirmPassword) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    if (newPassword !== confirmPassword) {
      wx.showToast({
        title: '两次密码输入不一致',
        icon: 'none'
      });
      return;
    }

    if (newPassword.length < 6) {
      wx.showToast({
        title: '新密码长度不能少于6位',
        icon: 'none'
      });
      return;
    }

    // 提交修改
    wx.request({
      url: this.data.backendUrl + 'change_password.php',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        user_id: userInfo.id,
        old_password: oldPassword,
        new_password: newPassword
      },
      success: (res) => {
        if (res.data.status === 'success') {
          wx.showToast({
            title: '密码修改成功',
            icon: 'success'
          });
          
          // 清除用户信息并跳转到登录页
          setTimeout(() => {
            wx.removeStorageSync('userInfo');
            wx.reLaunch({
              url: '/pages/login/login'
            });
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '修改失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  }
}); 